import time

from flask import Blueprint
from app.common.result import trueReturn, falseReturn
from app.api import handle_error, verify_params, api_URL, app_id, app_secret
from flask import request, g, jsonify
from app.models.IotDatas import IotData
from app.models.HumidityDatas import HumidityData
from app.models.IntruderDatas import IntruderData
from app.models.TemperatureDatas import TemperatrueData
from app.celery_tasks.tasks import check_status
from app.models.Student import  Student
from app.util.zhenzismsclient import ZhenziSmsClient as MessageClient

iotdata_blueprint = Blueprint('iotdata_blueprint', __name__, url_prefix='/iotdata')

@iotdata_blueprint.before_request
@handle_error
def before_request():
    if (request.method == 'POST' or request.method == 'PUT') and request.get_data():
        g.data = request.get_json()
    elif request.method == 'GET' or request.method == 'DELETE':
        g.data = request.args
    else:
        g.data = {}


@iotdata_blueprint.route('', methods=['GET'])
@handle_error
def get_recent_data():
    room = g.data.get('room')
    day = g.data.get('day', 1)
    page = g.data.get('page', 1)
    size = g.data.get('size', 20)
    iot_data = IotData.get_recent_data(room, day, page, size)
    data = []
    for item in iot_data:
        data.append(item.json())
    return trueReturn(data=data)

@iotdata_blueprint.route('/info', methods=['GET'])
@handle_error
def get_all():
    room = g.data.get('room')
    if room is None:
        room = ''
    room = str(room)
    intruder_data, count = IntruderData.get_all(room=room)
    stealWarnList = {
        'count': count,
        'list': [item.json() for item in intruder_data]
    }
    temperature_data, count = TemperatrueData.get_all(room=room)
    tempWarnList = {
        'count': count,
        'list': [item.json() for item in temperature_data]
    }
    humidity_data, count = HumidityData.get_all(room=room)
    humiWarnList={
        'count': count,
        'list': [item.json() for item in humidity_data]
    }
    data = {
        'humiWarnList': humiWarnList,
        'tempWarnList': tempWarnList,
        'stealWarnList': stealWarnList
    }
    return trueReturn(data=data)




@iotdata_blueprint.route('/intruder_danger', methods=['PUT'])
@handle_error
def update_intruder_status():
    room = g.data.get('room')
    room = str(room)
    ts = g.data.get('ts')
    IntruderData.set_stauts(roomId=room, ts=ts)
    return trueReturn()

@iotdata_blueprint.route('/humidity_danger', methods=['PUT'])
@handle_error
def update_humidity_status():
    print(g.data)
    room = g.data.get('room')
    room = str(room)
    ts = g.data.get('ts')
    HumidityData.set_stauts(roomId=room, ts=ts)
    return trueReturn()

@iotdata_blueprint.route('/temperature_danger', methods=['PUT'])
@handle_error
def update_temperature_status():
    room = g.data.get('room')
    room = str(room)
    ts = g.data.get('ts')
    TemperatrueData.set_stauts(roomId=room, ts=ts)
    return trueReturn()



@iotdata_blueprint.route('/intruder_danger', methods=['POST'])
@handle_error
def receive_intruder_danger():
    client = MessageClient(api_URL, app_id, app_secret)
    topic = g.data.get('topic')
    typ = topic.split('/')[0]
    roomid = topic.split('/')[1]
    ts = g.data.get('ts')
    type = g.data.get('type')
    distance = g.data.get('distance')
    roomId = int(roomid)
    students = Student.get_by_roomId(roomId)
    for student in students:
        if (student.phone != None) & (student.warnOpened == True):
            params = {
                'number': student.phone,
                'templateId': '5115',
                'templateParams': [student.name if student.name is not None else '同学', type]
            }
            client.send(params=params)
    time.sleep(1)
    intruder_data = IntruderData.check_status(topic=topic, ts=ts, type=type)
    if intruder_data.json()['status'] == 'nok':
        print('nok')
        pass
    return typ

@iotdata_blueprint.route('/humidity_danger', methods=['POST'])
@handle_error
def receive_humidity_danger():
    client = MessageClient(api_URL, app_id, app_secret)
    topic = g.data.get('topic')
    typ = topic.split('/')[0]
    roomid = topic.split('/')[1]
    ts = g.data.get('ts')
    type = g.data.get('type')
    humidity = g.data.get('humidity')
    roomId = int(roomid)
    students = Student.get_by_roomId(roomId)
    print(len(students))
    for student in students:
        if (student.phone != None) & (student.warnOpened == True):
            params = {
                'number': student.phone,
                'templateId': '5115',
                'templateParams': [student.name if student.name is not None else '同学', type]
            }
            client.send(params=params)
    time.sleep(1)
    humidity_data = HumidityData.check_status(topic=topic, ts=ts, type=type)
    if humidity_data.json()['status'] == 'nok':
        # 发送短信到管理员
        pass
    return typ

@iotdata_blueprint.route('/temperature_danger', methods=['POST'])
@handle_error
def receive_temperature_danger():
    client = MessageClient(api_URL, app_id, app_secret)
    topic = g.data.get('topic')
    typ = topic.split('/')[0]
    roomid = topic.split('/')[1]
    ts = g.data.get('ts')
    type = g.data.get('type')
    temperature = g.data.get('temperature')
    roomId = int(roomid)
    students = Student.get_by_roomId(roomId)
    for student in students:
        if (student.phone != None) & (student.warnOpened == True):
            params = {
                'number': student.phone,
                'templateId': '5115',
                'templateParams': [student.name if student.name is not None else '同学', type]
            }
            client.send(params=params)
    time.sleep(1)
    temperature_data = TemperatrueData.check_status(topic=topic, ts=ts, type=type)
    if temperature_data.json()['status'] == 'nok':
        # 发送短信到管理员
        pass
    return typ

@iotdata_blueprint.route('/monitor', methods=['GET'])
@handle_error
def get_monitor():
    room = g.data.get('room', None)
    return trueReturn(data="http://192.168.43.177:8090/stream.mjpg")


@iotdata_blueprint.route('/sos', methods=['POST'])
@handle_error
def send_sos():
    roomid = g.data.get('room', '523')
    client = MessageClient(api_URL, app_id, app_secret)
    params = {
        'number':  '13295823966',#'13295823966',
        'templateId': '5115',
        'templateParams': ['管理员', str(roomid) + '寝室需要您的帮助']
    }
    client.send(params=params)
    return trueReturn()




